package org.patchca.background;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

import org.patchca.background.BackgroundFactory;

/**
 * 绘制带噪点的背景
 * 
 * @author aaron
 * @varsion 0.1.0 2017年11月12日
 */
public class NoiseBackgroundFactory implements BackgroundFactory {
	private Random	random		= new Random();
	/** 噪点个数 */
	private int		noiseCount	= 50;
	/** 干扰线条数 */
	private int		lineCount	= 2;

	@Override
	public void fillBackground(BufferedImage image) {
		Graphics graphics = image.getGraphics();

		// 验证码图片的宽高
		int imgWidth = image.getWidth();
		int imgHeight = image.getHeight();

		// 填充为白色背景
		graphics.setColor(Color.WHITE);
		graphics.fillRect(0, 0, imgWidth, imgHeight);

		// 画100个噪点(颜色及位置随机)
		for (int i = 0; i < noiseCount; i++) {
			// 随机颜色
			int rInt = random.nextInt(255);
			int gInt = random.nextInt(255);
			int bInt = random.nextInt(255);
			graphics.setColor(new Color(rInt, gInt, bInt));

			// 随机位置
			int xInt = random.nextInt(imgWidth - 3);
			int yInt = random.nextInt(imgHeight - 2);

			// 随机旋转角度
			int sAngleInt = random.nextInt(360);
			int eAngleInt = random.nextInt(360);

			// 随机大小
			int wInt = random.nextInt(6);
			int hInt = random.nextInt(6);

			graphics.fillArc(xInt, yInt, wInt, hInt, sAngleInt, eAngleInt);

			int mod = (noiseCount / lineCount);
			if (mod < 10) {
				mod = 10;
			} else if (mod == noiseCount) {
				mod = noiseCount - 1;
			}
			if (i % mod == 0) {
				int xInt2 = random.nextInt(imgWidth);
				int yInt2 = random.nextInt(imgHeight);
				graphics.drawLine(xInt, yInt, xInt2, yInt2);
			}
		}
	}

	public int getNoiseCount() {
		return noiseCount;
	}

	/**
	 * 设置噪点个数，建议为干扰线条数的20倍
	 * 
	 * @param noiseCount
	 */
	public void setNoiseCount(int noiseCount) {
		if (noiseCount < 20) {
			noiseCount = 20;
		}
		if (noiseCount > 200) {
			noiseCount = 200;
		}
		this.noiseCount = noiseCount;
	}

	public int getLineCount() {
		return lineCount;
	}

	/**
	 * 设置干扰线调试，建议为1-5条
	 * 
	 * @param lineCount
	 */
	public void setLineCount(int lineCount) {
		if (lineCount < 1) {
			lineCount = 1;
		}
		if (lineCount > 10) {
			lineCount = 10;
		}
		this.lineCount = lineCount;
	}
}
